package dao;

import models.city.City;
import models.desease.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class CityDAO {

	DataSource dataSource;
	JdbcTemplate jdbc;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		jdbc = new JdbcTemplate(dataSource);
	}

	public HashMap<String, City> getAllCities(HashMap<String, Disease> disease) {
		String SQL = "SELECT id, name, topDistanse, leftDistanse, diseaseName FROM FACTORYDATA.CITIES";
		HashMap<String, City> cities = new HashMap<String, City>();
		List<City> getAllCities = jdbc.query(SQL, new RowMapper<City>() {
			@Override
			public City mapRow(ResultSet rs, int rowNum) throws SQLException {
				City city = new City(rs.getInt("id"), rs.getString("name"),
						disease.get(rs.getString("diseaseName")), rs
								.getInt("topDistanse"), rs
								.getInt("leftDistanse"));
				return city;
			}
		});
		updateCitiesNeighbours(getAllCities);
		for (City c : getAllCities) {
			cities.put(c.getName(), c);
		}
		return cities;
	}

	public void updateCitiesNeighbours(List<City> cities) {
		for (City c : cities) {
			String SQL = "SELECT n_id, n_name FROM FACTORYDATA.NEIGHBOURS WHERE n_id = "
					+ c.getId();
			List<String> list = jdbc.query(SQL, new RowMapper<String>() {
				@Override
				public String mapRow(ResultSet rs, int rowNum)
						throws SQLException {
					return rs.getString("n_name");
				}

			});
			c.setNeighbourNames(list);
		}
	}
}
